package org.jeecg.modules.htxincailiao.forums.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.RequestUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.htxincailiao.account.constant.HTAccountTypeEnum;
import org.jeecg.modules.htxincailiao.account.domain.vo.HTUserInfoVO;
import org.jeecg.modules.htxincailiao.account.entity.HTPlatformUser;
import org.jeecg.modules.htxincailiao.account.mapper.HTAccountMapper;
import org.jeecg.modules.htxincailiao.account.service.IHTAccountService;
import org.jeecg.modules.htxincailiao.forums.entity.HTForumsAnswer;
import org.jeecg.modules.htxincailiao.forums.entity.HTForumsQuestion;
import org.jeecg.modules.htxincailiao.forums.service.IHTForumsAnswerService;
import org.jeecg.modules.htxincailiao.forums.service.IHTForumsQuestionService;
import org.jeecg.modules.permissions.HTRolePermission;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @Description: ht_forums_answer
 * @Author: jeecg-boot
 * @Date: 2021-07-16
 * @Version: V1.0
 */
@Api(tags = "ht_forums_answer")
@RestController
@RequestMapping("/forums/hTForumsAnswer")
@Slf4j
public class HTForumsAnswerController extends JeecgController<HTForumsAnswer, IHTForumsAnswerService> {
    @Resource
    private IHTForumsAnswerService hTForumsAnswerService;

    @Resource
    private IHTForumsQuestionService hTForumsQuestionService;

    @Resource
    private IHTAccountService accountService;

    @Resource
    private ISysUserService sysUserService;

    /**
     * 分页列表查询
     *
     * @param hTForumsAnswer
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "ht_forums_answer-分页列表查询")
    @ApiOperation(value = "ht_forums_answer-分页列表查询", notes = "ht_forums_answer-分页列表查询")
    @RequestMapping(value = "/list", method = {RequestMethod.GET, RequestMethod.POST})
    public Result<?> queryPageList(HTForumsAnswer hTForumsAnswer,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        if (req.getMethod().equals("POST")) {
            String line = RequestUtil.getPostParam(req);
            if (oConvertUtils.isNotEmpty(line)) {
                hTForumsAnswer = JSONObject.parseObject(line, HTForumsAnswer.class);
                pageNo = hTForumsAnswer.getPageNo();
                pageSize = hTForumsAnswer.getPageSize();
            }
        }
        String token = req.getHeader(CommonConstant.X_ACCESS_TOKEN);
        String username = null;
        if (oConvertUtils.isNotEmpty(token)) {
            username = JwtUtil.getUsername(token);
        }

        HTPlatformUser loginUser = null;
        if (oConvertUtils.isNotEmpty(username)) {
            loginUser = accountService.queryFrontendUserByUsername(username);
        }

        String loginExpertId = HTRolePermission.GetLoginUserForumsExpertId(req);
        if (oConvertUtils.isEmpty(loginExpertId)) {
            hTForumsAnswer.setReplyUserId(loginExpertId);
        }

        QueryWrapper<HTForumsAnswer> queryWrapper = QueryGenerator.initQueryWrapper(hTForumsAnswer, req.getParameterMap());
        Page<HTForumsAnswer> page = new Page<HTForumsAnswer>(pageNo, pageSize);
        IPage<HTForumsAnswer> pageList = hTForumsAnswerService.page(page, queryWrapper);
        List<HTForumsAnswer> records = pageList.getRecords();
        HTPlatformUser finalLoginUser = loginUser;
        records.forEach(record -> {
            String userId = record.getReplyUserId();
            HTPlatformUser user = accountService.queryUserById(userId);
            if (oConvertUtils.isNotEmpty(finalLoginUser)) {
                String loginUserId = finalLoginUser.getId();
                if (userId.equals(loginUserId)) {
                    record.setOwner(true);
                }
            }


            if (oConvertUtils.isNotEmpty(user)) {
                HTAccountTypeEnum accountTypeEnum = HTAccountTypeEnum.values()[user.getAccountType()];
                HTUserInfoVO userInfoVO = accountService.getUserInfo(accountTypeEnum, userId);
               if(oConvertUtils.isNotEmpty(userInfoVO)) {
                   String answerName = null;
                   if (oConvertUtils.isNotEmpty(userInfoVO.getNickname())) {
                       answerName = userInfoVO.getNickname();
                   } else if (oConvertUtils.isNotEmpty(userInfoVO.getPhoneNumber())) {
                       answerName = userInfoVO.getPhoneNumber().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
                   } else if (oConvertUtils.isNotEmpty(userInfoVO.getUsername())) {
                       answerName = userInfoVO.getUsername();
                   }

                   record.setAnswerName(answerName);
               }

            }
        });

        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param hTForumsAnswer
     * @return
     */
    @AutoLog(value = "ht_forums_answer-添加")
    @ApiOperation(value = "ht_forums_answer-添加", notes = "ht_forums_answer-添加")
    @PostMapping(value = "/add")
    @Transactional
    public Result<?> add(HttpServletRequest request, @RequestBody HTForumsAnswer hTForumsAnswer) {
        String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
        if (oConvertUtils.isEmpty(token)) {
            return Result.error("请先登录！");
        }
        String username = JwtUtil.getUsername(token);

        //1. 通过登录账号、手机号、
        HTPlatformUser user = accountService.queryFrontendUserByUsername(username);
        if (Objects.isNull(user)) {
            return Result.error("用户未登录");
        } else {
            hTForumsAnswer.setReplyUserId(user.getId());
        }
        updateCommentCount(hTForumsAnswer, true);
        hTForumsAnswerService.save(hTForumsAnswer);
        return Result.OK("添加成功！");
    }

    private void updateCommentCount(HTForumsAnswer hTForumsAnswer, boolean isAdd) {
        HTForumsQuestion hTForumsQuestion = hTForumsQuestionService.getById(hTForumsAnswer.getQuestionId());
        if (hTForumsQuestion != null) {
            Integer commentCount = hTForumsQuestion.getCommentCount() + (isAdd ? 1 : -1);
            hTForumsQuestion.setCommentCount(commentCount);
            hTForumsQuestionService.updateById(hTForumsQuestion);
        }

    }

    /**
     * 专家回复
     *
     * @param hTForumsAnswer
     * @return
     */
    @AutoLog(value = "ht_forums_answer-添加")
    @ApiOperation(value = "ht_forums_answer-添加", notes = "ht_forums_answer-添加")
    @PostMapping(value = "/expert/reply")
    @Transactional
    public Result<?> expertReply(HttpServletRequest request, @RequestBody HTForumsAnswer hTForumsAnswer) {
        String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
        if (oConvertUtils.isEmpty(token)) {
            return Result.error("请先登录！");
        }
        String username = JwtUtil.getUsername(token);
        if (oConvertUtils.isEmpty(username)) {
            return Result.error("登录用户名不能为空");
        }

        String loginExpertId = HTRolePermission.GetLoginUserForumsExpertId(request);
        if (oConvertUtils.isEmpty(loginExpertId)) {
            SysUser sysUser = sysUserService.getUserByName(username);
            if (sysUser != null) {
                loginExpertId = sysUser.getId();
            }
            if (oConvertUtils.isEmpty(loginExpertId)) {
                return Result.error("问答专家账号不存在");
            }
        }


        hTForumsAnswer.setReplyUserId(loginExpertId);
        hTForumsAnswerService.save(hTForumsAnswer);
        updateCommentCount(hTForumsAnswer, true);

        return Result.OK("回复成功");
    }

    /**
     * 编辑
     *
     * @param hTForumsAnswer
     * @return
     */
    @AutoLog(value = "ht_forums_answer-编辑")
    @ApiOperation(value = "ht_forums_answer-编辑", notes = "ht_forums_answer-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody HTForumsAnswer hTForumsAnswer) {
        hTForumsAnswerService.updateById(hTForumsAnswer);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "ht_forums_answer-通过id删除")
    @ApiOperation(value = "ht_forums_answer-通过id删除", notes = "ht_forums_answer-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        handleForumsAnswerDelete(id);
        return Result.OK("删除成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "ht_forums_answer-通过id删除")
    @ApiOperation(value = "ht_forums_answer-通过id删除", notes = "ht_forums_answer-通过id删除")
    @RequestMapping(value = "/userDelete", method = {RequestMethod.GET, RequestMethod.POST})
    public Result<?> userDelete(HttpServletRequest req, @RequestParam(name = "id", required = false) String id) {
        String token = req.getHeader(CommonConstant.X_ACCESS_TOKEN);
        if (oConvertUtils.isEmpty(token)) {
            return Result.error("请先登录！");
        }
        String username = JwtUtil.getUsername(token);
        if (oConvertUtils.isEmpty(username)) {
            return Result.error("登录用户名不能为空");
        }

        if (req.getMethod().equals("POST")) {
            String line = RequestUtil.getPostParam(req);
            if (oConvertUtils.isNotEmpty(line)) {
                HTForumsAnswer answer = JSONObject.parseObject(line, HTForumsAnswer.class);
                id = answer.getId();
            }
        }

        HTPlatformUser user = accountService.queryFrontendUserByUsername(username);
        HTForumsAnswer forumsAnswer = hTForumsAnswerService.getById(id);
        if (forumsAnswer.getReplyUserId().equals(user.getId())) {
            handleForumsAnswerDelete(id);
        } else {
            return Result.error("不能删除他人的评论");
        }

        return Result.OK("删除成功!");
    }

    private void handleForumsAnswerDelete(String id) {
        HTForumsAnswer forumsAnswer = hTForumsAnswerService.getById(id);
        updateCommentCount(forumsAnswer, false);
        hTForumsAnswerService.removeById(id);
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "ht_forums_answer-批量删除")
    @ApiOperation(value = "ht_forums_answer-批量删除", notes = "ht_forums_answer-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
//        this.hTForumsAnswerService.removeByIds(Arrays.asList(ids.split(",")));
        List<String> list = Arrays.asList(ids.split(","));
        list.forEach(this::handleForumsAnswerDelete);

        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "ht_forums_answer-通过id查询")
    @ApiOperation(value = "ht_forums_answer-通过id查询", notes = "ht_forums_answer-通过id查询")
    @RequestMapping(value = "/queryById", method = {RequestMethod.GET, RequestMethod.POST})
    public Result<?> queryById(HttpServletRequest req, @RequestParam(name = "id", required = true) String id) {
        if (req.getMethod().equals("POST")) {
            String line = RequestUtil.getPostParam(req);
            if (oConvertUtils.isNotEmpty(line)) {
                HTForumsAnswer answer = JSONObject.parseObject(line, HTForumsAnswer.class);
                id = answer.getId();
            }
        }

        HTForumsAnswer hTForumsAnswer = hTForumsAnswerService.getById(id);
        if (hTForumsAnswer == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(hTForumsAnswer);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param hTForumsAnswer
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HTForumsAnswer hTForumsAnswer) {
        return super.exportXls(request, hTForumsAnswer, HTForumsAnswer.class, "ht_forums_answer");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, HTForumsAnswer.class);
    }

}
